package net.niufei.study.epatterns.transaction;

import java.util.concurrent.locks.ReentrantLock;

public class TestLock {

	public static void main(String[] args) {
		final Test t = new Test();
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				try {
					t.lock();
					t.print1("t1");
					t.print2("t1");
					Thread.sleep(5000L);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				t.unlock();
			}
		}).start();
		try {
			Thread.sleep(50);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				t.print1("t2");
				t.print2("t2");
			}
		}).start();
	}
	
	private static class Test {
		ReentrantLock lock = new ReentrantLock();
		
		public void lock() {
			lock.lock();
		}
		
		public void unlock() {
			lock.unlock();
		}
		
		public void print1(String name) {
			lock.lock();
			System.out.println(name + " print1");
		}
		
		
		public void print2(String name) {
			lock.lock();
			System.out.println(name + " print2");
		}
	}
}
